package cas.ihep.hmss.queue;

import cas.ihep.hmss.Job;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

public class ShortJobFirstQueue implements JobQueue{
    private final LinkedList<Job> jobQueue=new LinkedList<>();
    private final FileSystem fs=FileSystem.get(new Configuration());

    public ShortJobFirstQueue() throws IOException {
    }

    @Override
    public void enqueue(Job job) throws Exception {
        synchronized (jobQueue){
            jobQueue.offerLast(job);
        }
    }

    @Override
    public Job dequeue(int s) throws Exception {
        synchronized (jobQueue){
            int sz=jobQueue.size();
            if (sz<=0){
                return null;
            }
            long minLen=Long.MAX_VALUE;
            for(int i=0;i<sz;i++){
                Job job=jobQueue.get(i);
                if (job.length<0){
                    job.length=0;
                    if(job.destPath.contains("hdfs://")){
                        for(String ss:job.srcPath){
                            File file=new File(ss);
                            job.length+=file.length();
                        }
                    }else{
                        for(String ss:job.srcPath){
                            Path pp=new Path(ss);
                            job.length+= fs.getFileStatus(pp).getLen();
                        }
                    }
                }
                if (job.length<minLen){
                    minLen=job.length;
                    s=i;
                }
            }
            Job ret=jobQueue.get(s);
            jobQueue.remove(s);
            return ret;
        }
    }
}
